﻿using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// 游戏控制器
/// </summary>
public class GameController : BaseController {

    static GameController _inst;
    public static GameController inst { get { return _inst; } }

    /// <summary>
    /// 游戏流程
    /// </summary>
    private BaseProceduar _proceduar = null;

    ///////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// 切换流程
    /// </summary>
    /// <param name="newProceduar"></param>
    public void SwitchTo(BaseProceduar newProceduar, bool initUI = true)
    {
        if (_proceduar != null)
        {
            _proceduar.LeaveProceduar();
        }
        if (newProceduar != null)
        {
            newProceduar.EnterProceduar(initUI);
        }
        _proceduar = newProceduar;
    }

    /// <summary>
    /// UI系统就绪
    /// </summary>
    public void OnUIReady()
    {
        // 初始化调试界面
        DebugInfo.InitDebugView();

        // 进入登录流程
        SwitchTo(LoginProcedure.inst);
    }

    /// <summary>
    /// 将消息加入消息队列
    /// </summary>
    /// <param name="message"></param>
    public void EnqueueMessage(BaseProceduar.Message message)
    {
        if (_proceduar != null)
        {
            _proceduar.EnqueueMessage(message);
        }
    }

    public void Logout()
    {
        // 切换到登录流程
        SwitchTo(LoginProcedure.inst);

        // 清除数据
        LoginReqInfo.ClearCache();
        DataKernel.inst.Clear();
    }

    ///////////////////////////////////////////////////////////////////////////

    protected override void InitData()
    {
        // 不销毁本对象
        GameObject.DontDestroyOnLoad(gameObject);

        // 程序后台运行
        Application.runInBackground = true;

        _inst = this;
    }

    protected override void InitView()
    {
        SceneManager.LoadScene("Main");
    }

    protected override void UpdateData()
    {
        base.UpdateData();

        if (_proceduar != null)
        {
            _proceduar.UpdateProceduar();
        }
    }

    protected override void UpdateView()
    {
        base.UpdateView();

        DebugInfo.UpdateDebugInfo();
    }

    protected override void DestroyView()
    {
        DebugInfo.DestroyView();
    }
}
